package com.dlz.systemshop.controller;

import com.dlz.systemshop.pojo.Goods;
import com.dlz.systemshop.pojo.PageRequest;
import com.dlz.systemshop.pojo.PageResult;
import com.dlz.systemshop.service.GoodService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Map;

@RequestMapping("/goods")
@RestController
@Slf4j
public class GoodsController {
    @Autowired
    private GoodService goodService;

    @PostMapping("/add")
    public Boolean add(@RequestBody Goods goods) {
        log.info("添加商品 goods: {}", goods);
        Assert.notNull(goods, "商品不能为空");
        Assert.notNull(goods.getCategoryId(), "商品分类不能为空");
        Boolean flag = goodService.add(goods);
        return flag;
    }

    @PostMapping("/update")
    public Boolean update(@RequestBody Goods goods) {
        log.info("更新商品 goods: {}", goods);
        Assert.notNull(goods, "商品不能为空");
        Boolean flag = goodService.update(goods);
        return flag;
    }

    @GetMapping("/getGoods")
    public Goods getGoods(Integer id) {
        log.info("获取商品 id: {}", id);
        Assert.notNull(id, "商品Id不能为空");
        Goods goods = goodService.getGoods(id);
        return goods;
    }

    @GetMapping("/getGoodsListAll")
    public List<Goods> getGoodsListAll() {
        List<Goods> goodsListAll = goodService.getGoodsListAll();
        return goodsListAll;
    }

    @GetMapping("/getPageDivision")
    public PageResult<Goods> getPageDivision(PageRequest pageRequest) {
        List<Goods> goodsByPage = goodService.findGoodsByPage(pageRequest.getOffset(), pageRequest.getPageSize());
        Integer count = goodService.getCount();
        return new PageResult<Goods>(pageRequest.getCurrentPage(), pageRequest.getPageSize(), count, goodsByPage);
    }

    @RequestMapping("/delGoods")
    public Boolean delGoods( @RequestBody Map<String, String> params) {
        Integer id = Integer.parseInt(params.get("id"));
        log.info("删除商品 id: {}", id);
        return goodService.delGoods(id);
    }
}
